<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-button-group>
        <el-button type="primary" v-if="categoryManager_btn_add" icon="plus" @click="handlerAdd">添加</el-button>
        <el-button
          type="primary"
          v-if="categoryManager_btn_edit"
          icon="edit"
          @click="handlerEdit"
        >编辑</el-button>
        <el-button
          type="primary"
          v-if="categoryManager_btn_del"
          icon="delete"
          @click="handleDelete"
        >删除</el-button>
      </el-button-group>
    </div>

    <el-row>
      <el-col :span="4" style="margin-top:15px;">
        <el-input placeholder="输入店铺进行过滤" v-model="filterTextShop"></el-input>
        <el-tree
          class="filter-tree"
          :data="treeDataShop"
          node-key="id"
          highlight-current
          :props="defaultProps"
          :filter-node-method="filterNode"
          ref="shopTree"
          @node-click="getCategoryList"
        ></el-tree>
      </el-col>
      <el-col :span="4" style="margin-top:15px;">
        <el-input placeholder="输入类别进行过滤" v-model="filterTextCategory"></el-input>
        <el-tree
          class="filter-tree"
          :data="treeDataCategory"
          node-key="id"
          highlight-current
          :props="defaultProps"
          :filter-node-method="filterNode"
          ref="categoryTree"
          @node-click="getNodeData"
        ></el-tree>
      </el-col>
      <el-col :span="16" style="margin-top:15px;">
        <el-card class="box-card">
          <el-form
            :label-position="labelPosition"
            label-width="80px"
            :model="form"
            ref="form"
            :rules="rules"
          >
            <el-form-item label="店铺id" prop="shopId">
              <el-input v-model="form.shopId" placeholder="请选择店铺" readonly></el-input>
            </el-form-item>
            <el-form-item label="类别名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入类别名称"></el-input>
            </el-form-item>
            <el-form-item label="父级节点" prop="supId">
              <el-input v-model="form.supId" placeholder="请输入父级节点" readonly></el-input>
            </el-form-item>
            <el-form-item label="类别图片(520*162)">
              <el-upload
                class="avatar-uploader"
                name="imageFile"
                :headers="requestHeader"
                :action="uploadImgUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :data="uploadParam"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="分类等级" prop="cateLevel">
              <el-input v-model="form.cateLevel" placeholder="请输入分类等级"></el-input>
            </el-form-item>
            <el-form-item label="排序" prop="orderLevel">
              <el-input v-model="form.orderLevel" placeholder="请输入排序"></el-input>
            </el-form-item>
            <el-form-item label="广告位图片">
              <el-upload
                class="avatar-uploader"
                name="imageFile"
                :headers="requestHeader"
                :action="uploadImgUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccesse"
                :before-upload="beforeAvatarUploade"
                :data="uploadParam"
              >
                <img v-if="imageUrle" :src="imageUrle" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="广告位商品">
              <el-select v-model="shopsByGooid" clearable filterable placeholder="请选择商品">
                <el-option
                  v-for="item in shopsBy"
                  :key="item.goodsId"
                  :label="item.name"
                  :value="item.goodsId"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                class="filter-item"
                v-model="form.status"
                placeholder="请选择状态"
                value-key="status"
              >
                <el-option
                  v-for="item in  statusOptions"
                  :key="item.status"
                  :label="item.label"
                  :value="item.status"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="显示状态" prop="showStatus">
              <el-select
                class="filter-item"
                v-model="form.showStatus"
                placeholder="请选择显示状态"
                value-key="showStatus"
              >
                <el-option
                  v-for="item in  showStatusOptions"
                  :key="item.showStatus"
                  :label="item.label"
                  :value="item.showStatus"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="formStatus == 'update'">
              <el-button type="primary" @click="update">更新</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
            <el-form-item v-if="formStatus == 'create'">
              <el-button type="primary" @click="create">保存</el-button>
              <el-button @click="onCancel">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  fetchTree,
  getObj,
  addObj,
  delObj,
  putObj
} from "api/shop/goods/category/index";
import { getSelectByshops } from "api/shop/goods/goods/index";
import { fetchTree as fetchShopTree } from "api/shop/shops/index";
import { getToken } from "utils/auth";
import { mapGetters } from "vuex";
export default {
  name: "goodsCategory",
  data() {
    return {
      filterTextCategory: "",
      filterTextShop: "",
      list: null,
      total: null,
      formEdit: true,
      formAdd: true,
      formStatus: "",
      statusOptions: [
        { status: 1, label: "启用" },
        { status: 0, label: "待审核" },
        { status: -1, label: "停用" }
      ],
      showStatusOptions: [
        { showStatus: 1, label: "显示" },
        { showStatus: 0, label: "不显示" }
      ],
      listQuery: {
        name: undefined,
        shopId: undefined
      },
      treeDataCategory: [],
      treeDataShop: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      labelPosition: "right",
      shopsBy: [],
      shopsByGooid: [],
      form: {
        shopId: undefined,
        merchantId: undefined,
        code: undefined,
        icode: undefined,
        supId: undefined,
        name: undefined,
        status: 1,
        showStatus: 1,
        orderLevel: 100,
        cateLevel: undefined,
        pic: undefined,
        advertPic: undefined,
        advertLinkObjId: undefined
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入类别名称",
            trigger: "blur"
          },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ],
        supId: [
          {
            required: true,
            message: "请选择父节点",
            trigger: "blur",
            type: "number"
          }
        ],
        shopId: [
          {
            required: true,
            message: "请选择店铺",
            trigger: "blur",
            type: "number"
          }
        ]
      },
      currentId: 0,
      imgBaseURL: this.GLOBAL.imgBaseURL,
      uploadImgUrl: this.GLOBAL.uploadImgUrl,
      requestHeader: { token: getToken() },
      uploadParam: { useType: "category" },
      imageUrl: "",
      imageUrle: "",
      categoryManager_btn_add: false,
      categoryManager_btn_edit: false,
      categoryManager_btn_del: false
    };
  },
  watch: {
    filterTextCategory(val) {
      this.$refs.categoryTree.filter(val);
    },
    filterTextShop(val) {
      this.$refs.shopTree.filter(val);
    }
  },
  created() {
    // this.getCategoryList();
    this.getShopList();
    this.categoryManager_btn_add = this.elements["categoryManager:btn_add"];
    this.categoryManager_btn_del = this.elements["categoryManager:btn_del"];
    this.categoryManager_btn_edit = this.elements["categoryManager:btn_edit"];
  },
  computed: {
    ...mapGetters(["elements"])
  },
  methods: {
    getCategoryList(data) {
      this.resetForm();
      this.listQuery.shopId = data.id;
      this.form.shopId = data.id;
      this.form.merchantId = data.merchantId;
      fetchTree(this.listQuery).then(data => {
        this.getSelectByShopsId();
        this.treeDataCategory = data;
      });
    },
    getSelectByShopsId() {
      getSelectByshops(this.form.shopId).then(response => {
        this.shopsBy = response.data;
      });
    },
    refleshCategoryList() {
      fetchTree(this.listQuery).then(data => {
        this.getSelectByShopsId();
        this.treeDataCategory = data;
      });
    },
    getShopList() {
      fetchShopTree().then(data => {
        console.log(data);
        this.treeDataShop = data;
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    getNodeData(data) {
      if (!this.formEdit) {
        this.formStatus = "update";
      }
      getObj(data.id).then(response => {
        
        this.form = response.data;
        this.shopsByGooid = parseInt(response.data.advertLinkObjId);
        if (this.form.pic == "" || this.form.pic == null) {
          this.imageUrl = "";
        } else {
          this.imageUrl = this.imgBaseURL + this.form.pic;
        }

        if (this.form.advertPic == "" || this.form.advertPic == null) {
          this.imageUrle == "";
        } else {
          this.imageUrle = this.imgBaseURL + this.form.advertPic;
        }
      });
      this.currentId = data.id;
    },

    getCata(data) {
      if (!this.formEdit) {
        this.formStatus = "update";
      }
      getObj(data.id).then(response => {
        this.form = response.data;
      });
      this.currentId = data.id;
    },
    handlerEdit() {
      if (this.form.categoryId) {
        this.formEdit = false;
        this.formStatus = "update";
      }
    },
    handlerAdd() {
      this.resetForm();
      this.formEdit = false;
      this.formStatus = "create";
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.pic = res.data;
    },
    handleAvatarSuccesse(res, file) {
      this.imageUrle = URL.createObjectURL(file.raw);
      this.form.advertPic = res.data;
    },
    handleDelete() {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delObj(this.currentId).then(() => {
          this.refleshCategoryList();
          this.resetForm();
          this.onCancel();
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
        });
      });
    },
    update() {
      if (this.shopsByGooid != "" || shopsByGooid != null) {
        this.form.advertLinkObjId = this.shopsByGooid;
      }
      putObj(this.form.id, this.form).then(() => {
        this.refleshCategoryList();
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 2000
        });
      });
    },
    create() {
      if (this.shopsByGooid != "" || shopsByGooid != null) {
        this.form.advertLinkObjId = this.shopsByGooid;
      }
      addObj(this.form).then(data => {
        this.refleshCategoryList();
        if (data.status === 0) {
          this.$notify({
            title: "成功",
            message: data.message,
            type: "success",
            duration: 2000
          });
        } else {
          this.$notify({
            title: "失败",
            message: data.message,
            type: "error",
            duration: 2000
          });
        }
      });
    },
    onCancel() {
      this.formEdit = true;
      this.formStatus = "";
    },
    resetForm() {
      this.form = {
        code: undefined,
        icode: undefined,
        supId: this.currentId,
        name: undefined,
        status: 1,
        showStatus: 1,
        orderLevel: 100,
        cateLevel: undefined,
        pic: undefined,
        advertPic: undefined,
        advertLinkObjId: undefined
      };
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size  / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    },
    beforeAvatarUploade(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return (isJPG || isPNG) && isLt2M;
    }
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>